<?php

namespace App\Http\Model;

use App\Http\Model\Api\UserConvene;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class ShareDiamond extends Base
{
    protected $table = 'share_diamond_log2';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function getCreatedAtAttribute($value) {
      return date('Y年m月d日 H:i', strtotime($value));
    }

    //查看用户赠送记录
    public function showDiamondLog($user_id,$invite_uid)
    {
        $data = DB::table("share_diamond_log2")
            ->where(['user_id'=>$user_id,'invite_uid'=>$invite_uid])
            ->get();
        if(!$data)
            return [];
        return  self::objToArray($data);
    }

    //添加赠送记录
    public function createDiamond($data)
    {
        $data['created_at'] = $data['updated_at'] = date_ymd();
        $res = DB::table($this->table)->insertGetId($data);
        if(!$res){
            write_log('consumer', 'createDiamondError', json_encode($data));
            return false;
        }
        return $res;
    }

    /*
         * 查看用户累计金额
         * */
    public function countUserMoney($user_id)
    {
        return DB::table($this->table)->where(['user_id'=>$user_id,'d_rank'=>1])->sum('recharge_money');
    }


    /*
       * 查看用户是否充值
       * */
    public function showUserRecharge($user_id)
    {
        $data =  DB::table($this->table)->where(['user_id'=>$user_id])->get();
        return  self::objToArray($data);
    }

    /*
     * 查看用户是否充值
     * */
    public function getUserMoneyCount($user_ids){
      $data =DB::table($this->table)
            ->whereIn('user_id',$user_ids)
            ->get();
        return  self::objToArray($data);

    }

    public function user() {
      return $this->belongsTo(UserM::class, 'user_id', 'user_id');
    }

    public function invite() {
      return $this->belongsTo(UserM::class, 'invite_uid', 'user_id')->withDefault([
        'user_id' => 0,
        'nickname' => ''
      ]);
    }

    /**
     * 我的召集
     *
     * @param integer $user_id
     * @return void
     */
    public function getBeCalledInfo(int $user_id) {
      $model = new UserConvene();
      $user_convene_res = $model->getActiveUserConvene($user_id, 1)->toArray();
      $user_ids = array_column($user_convene_res, 'user_id');

      $invite_res = self::selectRaw("invite_uid,user_id,SUM(award_diamond) AS award_diamond")
      ->whereIn("user_id", $user_ids)
      ->groupBy("user_id")
      ->get()
      ->toArray();
      $invite_res = array_column($invite_res, null, 'user_id');
      $data = [];
      foreach($user_convene_res as $user) {
        array_push($data, [
          'nickname' => $user['user']['nickname'] ?? '',
          'portrait' => $user['user']['portrait'] ?? '',
          'award_diamond' => $invite_res[$user['user_id']]['award_diamond'] ?? 0,
          'user_id' => $user['user']['user_id'] ?? 0,
          'user' => [
            'nickname' => $user['user']['nickname'] ?? '',
            'portrait' => $user['user']['portrait'] ?? '',
            'user_id' => $user['user']['user_id'] ?? 0,
            'create_timestamp' => $user['user']['create_timestamp'] ?? 0
          ]
        ]);
      }
      return $data;
    }

    public function statisticsMyCalledInfo(int $user_id) {
      // 累计召集收益
      $grand_total = self::where('invite_uid', $user_id)->sum("award_diamond");

      // 本月召集收益
      $begin_date = date('Y-m-01 00:00:00');
      $end_date = date("Y-m-d 24:00:00", strtotime("-1 day", strtotime("+ 1 month", time())));
      $current_month_total = self::where("invite_uid", $user_id)->whereBetween("created_at",[$begin_date, $end_date])->sum("award_diamond");
      return [ 'grand_total' => $grand_total, 'current_month_total' => $current_month_total ];
    }

     /**
     * 他的召集统计已召集人数、累计收益
     *
     * @param integer $user_id
     * @return array
     */
    public function statisticsCalledInfo(int $user_id) {
      $res = self::selectRaw("COUNT(DISTINCT user_id) user_total, SUM(award_diamond) AS award_diamond_total")
      ->where('invite_uid', $user_id)
      ->groupBy('invite_uid')
      ->first();
      return $res ?: [
        'user_total' => 0,
        'award_diamond_total' => 0
      ]; 
    }

    /**
     * 充值返利明细
     *
     * @param integer $user_id
     * @return void
     */
    public function calledDetail(int $user_id) {
      return self::where('invite_uid', $user_id)
      ->orderBy('created_at', 'DESC')
      ->get(['award_diamond', 'created_at']);
    }

    /**
     * 轮播
     *
     * @return void
     */
    public function carousel() {
      return self::with(['invite:user_id,nickname'])
      ->orderBy('id', 'DESC')
      ->limit(10)
      ->get(['award_diamond','invite_uid']);
    }
}